package com.ruoyi.system.service.impl;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.system.domain.FileManage;
import com.ruoyi.system.domain.FileOnPlace;
import com.ruoyi.system.mapper.FileManageMapper;
import com.ruoyi.system.mapper.FileOnPlaceMapper;
import com.ruoyi.system.service.FileOnPlaceService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 文件归档(FileOnPlace)表服务实现类
 * @since 2023-03-23 14:51:04
 */
@Service("fileOnPlaceService")
public class FileOnPlaceServiceImpl implements FileOnPlaceService {
    @Resource
    private FileOnPlaceMapper fileOnPlaceMapper;

    @Resource
    private FileManageMapper fileManageMapper;
    /**
     * 通过ID查询单条数据
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public FileOnPlace queryById(Integer id) {
        return this.fileOnPlaceMapper.queryById(id);
    }

    /**
     * 分页查询
     * @param fileOnPlace 筛选条件
     * @return 查询结果
     */
    @Override
    public List<FileOnPlace> queryByPage(FileOnPlace fileOnPlace) {
        List<FileOnPlace> fileOnPlaces = this.fileOnPlaceMapper.queryAllByLimit(fileOnPlace);
        for (FileOnPlace onPlace : fileOnPlaces) {
            if (onPlace.getFiles() == null) {
                onPlace.setFiles(new ArrayList<>());
            }
            if (StrUtil.isNotEmpty(onPlace.getFileName())) {
                Arrays.stream(onPlace.getFileName().split(",")).forEach(id -> {
                    if (NumberUtil.isInteger(id)) {
                        FileManage byId = fileManageMapper.getById(Integer.valueOf(id));
                        onPlace.getFiles().add(byId);
                        onPlace.setFiles(onPlace.getFiles());
                    }
                });
            }
        }
        return fileOnPlaces;
    }

    /**
     * 新增数据
     * @param fileOnPlace 实例对象
     * @return 实例对象
     */
    @Override
    public FileOnPlace insert(FileOnPlace fileOnPlace) {
        this.fileOnPlaceMapper.insert(fileOnPlace);
        return fileOnPlace;
    }

    /**
     * 修改数据
     * @param fileOnPlace 实例对象
     * @return 实例对象
     */
    @Override
    public FileOnPlace update(FileOnPlace fileOnPlace) {
        this.fileOnPlaceMapper.update(fileOnPlace);
        return this.queryById(fileOnPlace.getId());
    }

    /**
     * 通过主键删除数据
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.fileOnPlaceMapper.deleteById(id) > 0;
    }
}
